#!/usr/bin/env python2.5
#coding: utf8

#Author: Gang Li
#Date: 2010-04-10 18:20

import sys
import os
import urllib
import urllib2

import core.controller.MultipartPostHandler as mph

def deploy(args):
    path = args[0]
    dest = args[1]
    if not dest.endswith("/"):
        dest += "/"

    opener = urllib2.build_opener(mph)
    if path:

        if os.path.isfile(path):
            data = {"file":open(path,"rb")}
            pkg_name = os.path.split(path)[1]
            r = opener.open(dest+pkg_name, data)
            print "upload",path, (r.code == 200 and "success" or "failed")
            return

        p,pkg_name = os.path.split(path)
        while p:
            if not pkg_name:
                p,pkg_name = os.path.split(p)
            else:
                break


    dirs = [[path,pkg_name]]
    while 1:
        if not len(dirs): break

        d,relative = dirs.pop()
        files = os.listdir(d)
        for f in files:
            _f = os.path.join(d,f)
            
            if os.path.isfile(_f):
                data = {"file":open(_f,"rb")}
                r = opener.open(dest+relative+"/"+f, data)
                print "upload",_f, (r.code == 200 and "success" or "failed")
            elif os.path.isdir(_f):
                dirs.append([_f,relative+"/"+f])

options = {"deploy": deploy }
def run():
    for k in sys.argv[1:]:
        if k in options:
            options[k](sys.argv[2:])